package com.sftz.modules.minapp.resourceRecord.service;

import io.searchbox.core.SearchResult;
import io.searchbox.core.search.aggregation.MetricAggregation;
import io.searchbox.core.search.aggregation.ValueCountAggregation;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.SqlManager;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.google.common.io.Resources;
import com.sftz.assets.enums.ResourcesSortEnum;
import com.sftz.framework.vendors.elasticsearch.EsSearchUtil;
import com.sftz.modules.datacollect.DataCollectClient;
import com.sftz.modules.datacollect.analytics.dto.StudyScoreCollectDto;
import com.sftz.modules.datacollect.analytics.service.StudyMessageService;
import com.sftz.modules.minapp.resourceRecord.dto.CourseStudyDetailsDto;
import com.sftz.modules.minapp.resourceRecord.dto.PersonCourseScoreDto;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.db.util.DbSqlUtil;

/**
 * @author   DuKL 资源学习进度
 * @Date	 2018年12月21日
 */
@IocBean
public class CourseResourceStudyViewService {
	private static final Log log = Logs.get();

	@Inject
	private StudentStudyCourseViewService studentStudyCourseViewService;

	@Inject
	private StudentOtherCourseScoreViewService studentOtherCourseScoreViewService;

	@Inject
	private IDbDao dbDao;

	@Inject
	private SqlManager sqlManager;

	public Object personCourseMessage(int courseId, int userId) {
		Map<String, Object> obj = new HashMap<String, Object>();
		//-----------------------------------查询课程资源信息------------------------------------------
		List<CourseStudyDetailsDto> courseResources = courseResources(courseId);
		//----------------------------------查询学生学习信息----------------------------------------
		StudyMessageService studyTimeService = DataCollectClient.getStudyMessageService();

		//查询该课程下已观的视频Id以及观看时间
		List<StudyScoreCollectDto> studyVideoVid = studyTimeService.studyVideoVid(courseId, userId);
		List<StudyScoreCollectDto> studyaudioVid = studyTimeService.studyaudioVid(courseId, userId);

		//计算已学习时间百分比
		for (CourseStudyDetailsDto courseStudy : courseResources) {
			//将资源时长向上取整
			double timeCount = courseStudy.getTimecount();
			if (timeCount == 0) {
				log.info("资源Id=" + courseStudy.getId() + ":" + courseStudy.getResourceName() + "的资源时长为空");
			}
			timeCount = Math.ceil(timeCount);
			courseStudy.setTimecount(timeCount);
			//--------------视频---------------
			if (courseStudy.getResourceType() == ResourcesSortEnum.VIDEO.intKey()) {
				//视频观看进度百分比
				for (StudyScoreCollectDto studyVideo : studyVideoVid) {
					if (courseStudy.getVid().equals(studyVideo.getVid())) {
						if (studyVideo.getTimeCount() >= courseStudy.getTimecount()) {
							courseStudy.setVideoLook(100);
						} else {
							double vBfb = studyVideo.getTimeCount() / courseStudy.getTimecount();
							BigDecimal bg = new BigDecimal(vBfb).setScale(2, RoundingMode.UP);
							courseStudy.setVideoLook(bg.doubleValue() * 100);
						}
					}
				}
			} else {//--------------音频---------------
				if (courseStudy.getResourceType() == ResourcesSortEnum.AUDIO.intKey()) {
					for (StudyScoreCollectDto studyAudio : studyaudioVid) {
						if (courseStudy.getVid().equals(studyAudio.getAudioId())) {
							if (studyAudio.getTimeCount() >= courseStudy.getTimecount()) {
								courseStudy.setVideoLook(100);
							} else {
								double vBfb = studyAudio.getTimeCount() / courseStudy.getTimecount();
								BigDecimal bg = new BigDecimal(vBfb).setScale(2, RoundingMode.UP);
								courseStudy.setVideoLook(bg.doubleValue() * 100);
							}
						}
					}
				}

			}
		}
		//用户最近学习时间
		String studyLastTime = studyTimeService.studyMessage(courseId, userId);
		obj.put("studyLastTime", studyLastTime);
		obj.put("courseStudy", courseResources);
		return obj;
	}

	/**
	 * 开大项目
	 * @author   DuKL
	 * @Date	 2018年8月28日
	 * (effect:课程下音频和视频资源)
	 */
	public List<CourseStudyDetailsDto> courseResources(Integer courseId) {
		List<CourseStudyDetailsDto> findCourseStructures = findCourseStructures(courseId);
		return findCourseStructures;
	}

	@Aop("logTime")
	public double findCourseResTime(Integer courseId) {
		Sql studentHwScore = Sqls.create(sqlManager.get("minapp_resourceRecord_find_course_resource_time_count"));
		studentHwScore.setParam("courseId", courseId);
		studentHwScore.setParam("audio", ResourcesSortEnum.AUDIO.intKey());
		studentHwScore.setParam("video", ResourcesSortEnum.VIDEO.intKey());
		double fetchDouble = DbSqlUtil.fetchDouble(dbDao, studentHwScore);
		BigDecimal bg = new BigDecimal(fetchDouble).setScale(2, RoundingMode.UP);
		return bg.doubleValue();
	}

	/**
	 * @author   DuKL
	 * @Date	 2018年11月8日
	 * (effect:查询课程所有结构)
	 */
	public List<CourseStudyDetailsDto> findCourseStructures(Integer courseId) {
		List<CourseStudyDetailsDto> re = new ArrayList<>();
		if (!Util.isEmpty(courseId) && courseId > 0) {
			Sql sql = Sqls.create(sqlManager.get("minapp_resourceRecord_coursemanage_common_all_structure_study"));
			sql.params().set("courseId", courseId);
			re = DbSqlUtil.query(dbDao, CourseStudyDetailsDto.class, sql);
		}
		return re;
	}

	public Integer TimeCount(Integer courseId, Integer userId) throws IOException {
		String indexName = "logstash-study*";
		String tmplPath = "elasticsearch/templates/dukl/scoreBook/log_query_Qc_studyTimeCount.js";
		URL url = Resources.getResource(tmplPath);
		String query = Resources.toString(url, Charset.forName("utf-8"));
		query = query.replaceAll("@courseId", courseId + "");
		query = query.replaceAll("@userId", userId + "");
		SearchResult searchResult = EsSearchUtil.searchResult(query, indexName);
		MetricAggregation aggregations = searchResult.getAggregations();
		ValueCountAggregation valueCountAggregation = aggregations.getValueCountAggregation("study_count");
		Long valueCount = valueCountAggregation.getValueCount();
		return valueCount.intValue();
	}

	public PersonCourseScoreDto studentStudyScore(Integer courseId, Integer userId) {
		return studentOtherCourseScoreViewService.findStudentScore(courseId, userId);
	}
}
